<template>
  <div class="app-container">
    <!-- 高级查询 -->
    <el-form v-show="searchVisible" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="费用名称:">
        <el-input v-model="queryParams.frtName" size="small" placeholder="请输入费用名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="openUploadDialog">导入</el-button>
      </el-col>
      <right-toolbar :show-search.sync="searchVisible" @queryTable="handleQuery" />
    </el-row>

    <!-- 数据列表 -->
    <el-table v-loading="loading" :data="dataList" highlight-current-row>
      <el-table-column label="客户名称" align="center" prop="customerName" width="180" />
      <el-table-column label="费用编码" align="center" prop="frtNo" width="180" />
      <el-table-column label="结算基于" align="center" prop="settleBy" width="180">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-select v-model="row.settleBy" size="small" style="width: 100%;" clearable>
              <el-option v-for="option in $constant.settleByOptions" :key="option.key" :label="option.label" :value="option.key" />
            </el-select>
          </template>
          <span v-else>{{ row.settleBy }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结算时间单位" align="center" prop="chargeTimeBy" width="180">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-select v-model="row.chargeTimeBy" size="small" style="width: 100%;" clearable>
              <el-option v-for="option in $constant.chargeTimeByOptions" :key="option.key" :label="option.label" :value="option.key" />
            </el-select>
          </template>
          <span v-else>{{ row.chargeTimeBy }}</span>
        </template>
      </el-table-column>
      <el-table-column label="金额/百分比" align="center" prop="amount" width="180">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-input v-model="row.amount" type="number" class="edit-input" size="small" />
          </template>
          <span v-else>{{ row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期到" align="center" prop="validUntil" width="180">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-date-picker v-model="row.validUntil" type="date" size="small" value-format="yyyy-MM-dd" style="width: 100%" placeholder="选择有效期到" clearable />
          </template>
          <span v-else>{{ parseTime(row.validUntil, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物料名称" align="center" prop="frtName" width="180">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-select v-model="row.materialNo" style="width: 100%;" clearable>
              <el-option v-for="option in options.materialOptions" :key="option.contractNo" :label="option.contractName" :value="option.contractNo" />
            </el-select>
          </template>
          <span v-else>{{ row.materialNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同" align="center" prop="frtName" width="180">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-select v-model="row.contractNo" style="width: 100%;" clearable>
              <el-option v-for="option in options.contractOptions" :key="option.id" :label="option.skuName" :value="option.id" />
            </el-select>
          </template>
          <span v-else>{{ row.materialNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始数量" align="center" prop="startQuantity" width="180">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-input v-model="row.startQuantity" type="number" class="edit-input" size="small" />
          </template>
          <span v-else>{{ row.startQuantity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最大数量" align="center" prop="endQuantity" width="180">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-input v-model="row.endQuantity" type="number" class="edit-input" size="small" />
          </template>
          <span v-else>{{ row.endQuantity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计费类型" align="center" prop="chargeType" width="180">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-select v-model="row.inAndOutCharge" style="width: 100%;" clearable>
              <el-option v-for="option in $constant.inAndOutChargeOptions" :key="option.key" :label="option.label" :value="option.key" />
            </el-select>
          </template>
          <span v-else>{{ row.inAndOutCharge }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width" fixed>
        <template slot-scope="{row}">
          <el-button v-if="row.edit" type="success" size="small" icon="el-icon-circle-check-outline" @click="handleEdit(row)">确认</el-button>
          <el-button v-else type="primary" size="small" icon="el-icon-edit" @click="row.edit=!row.edit">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="uploadDialog.title" :visible.sync="uploadDialog.visible" width="400px" append-to-body>
          <div v-loading="uploadLoading">
            <el-upload
              ref="upload"
              :limit="1"
              :headers="uploadData.headers"
              :action="uploadData.url + '?updateSupport=' + uploadData.updateSupport"
              :data="uploadData.params"
              :disabled="uploadData.isUploading"
              :on-progress="handleFileUploadProgress"
              :on-success="handleFileSuccess"
              :on-error="handleFileError"
              :auto-upload="false"
              accept=".xlsx, .xls"
              drag
            >
            <i class="el-icon-upload" />
                  <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                  </div>

                  <!-- <div slot="tip" class="el-upload__tip">
                    <el-link type="info" style="font-size:16px" @click="handleDownloadTemplate">下载模板</el-link>
                  </div> -->

                  <div slot="tip" class="el-upload__tip" style="color:red">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
                </el-upload>
                <div slot="footer" class="dialog-footer">
                  <el-button type="primary" @click="confirmUploadDialog">确 定</el-button>
                  <el-button @click="resetUploadDialog">取 消</el-button>
                </div>
              </div>
    </el-dialog>
  </div>
</template>

<script>
import ChargeConfigApi from '@/api/pms/ChargeConfigApi'
import TWhWarehouseCustomerMaterialApi from '@/api/pms/TWhWarehouseCustomerMaterialApi'
import ConContractApi from '@/api/contract/ConContractApi'
import AuthUtils from '@/utils/AuthUtils'

const defaultChargeConfigFormData = {
  customerId: null,
  customerName: null,
  frtNo: '仓储费',
  frtName: null,
  settleBy: null,
  chargeTimeBy: null,
  amount: null,
  chargeType: null,
  customerType: null,
  inAndOutCharge: null,
  validUntil: null,
  convertQuantity: null,
  startQuantity: null,
  endQuantity: null,
  startDateFrom: null
}
export default {
  name: 'ChargeConfigList',
  props: {
    customer: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  watch: {
    customer() {
      this.handleQuery()
    }
  },
  data() {
    return {
      options: {
        materialOptions: [],
        contractOptions: [],
        sysYnTypeOptions: this.$constant.sysYnTypeOptions
      },
      queryParams: {
        frtNo: '仓储费',
        frtName: null,
        isValid: this.$constant.Y
      },
      dataList: [],
      uploadDialog: {
        title: '批量导入',
        visible: false
      },
      uploadData: {
        headers: { Authorization: 'Bearer ' + AuthUtils.getToken() }, // 上传请求头
        url: process.env.VUE_APP_BASE_API + '/basic/customer/importCustomerMaterialData', // 上传的地址
        isUploading: false, // 是否禁用上传
        updateSupport: 0 // 是否更新已经存在的数据
      },
      loading: true,
      searchVisible: true,
      uploadLoading: false
    }
  },
  created() {
    this.handleQuery()
    this.loadOptions()
  },
  methods: {
    loadOptions() {
      const params = {
        customerNo: this.customer.id
      }
      TWhWarehouseCustomerMaterialApi.list(params).then(response => {
        this.options.materialOptions = response.data
      })
      ConContractApi.list(params).then(response => {
        this.options.contractOptions = response.data
      })
    },
    handleAdd() {
      console.log(this.customer)
      this.dataList.push({
        ...defaultChargeConfigFormData,
        customerId: this.customer.id,
        customerName: this.customer.customerName,
        edit: true
      })
    },
    handleRemove(row) {
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return ChargeConfigApi.remove(row.id)
      }).then(() => {
        this.handleQuery()
        this.$message.success('删除成功')
      })
    },
    handleEdit(row) {
      if (row.id) {
        ChargeConfigApi.edit(row).then(response => {
          this.$message.success('修改成功')
          this.handleQuery()
        })
      } else {
        ChargeConfigApi.add(row).then(response => {
          this.$message.success('添加成功')
          this.handleQuery()
        })
      }
    },
    handleQuery() {
      this.loading = true
      if (this.customer.id) {
        const params = {
          ...this.queryParams,
          customerId: this.customer.id
        }
        ChargeConfigApi.list(params).then(response => {
          this.dataList = response.data.map(item => {
            return {
              ...item,
              edit: false
            }
          })
          this.loading = false
        }, () => {
          this.loading = false
        })
      }
    },
    handleFileUploadProgress(event, file, fileList) {
      this.uploadData.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.uploadLoading = false
      this.uploadDialog.visible = false
      this.uploadData.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.data ? response.data : response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.queryParams.status = null
      this.handleQuery()
    },
    // 文件上传失败处理
    handleFileError(response, file, fileList) {
      this.uploadLoading = false
    },
    handleExport() {
      this.$confirm('是否确认导出数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return ChargeConfigApi.exportData(this.queryParams)
      }).then(response => {
        this.$common.download(response.msg)
      })
    },
    confirmUploadDialog() {

        this.uploadLoading = true
        this.$refs.upload.submit()

    },
    openUploadDialog() {
      this.resetUploadDialog()
      this.uploadDialog.visible = true
    },
    resetUploadDialog() {
      this.uploadDialog.visible = false
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    }
  }
}
</script>
